#include <iostream>
#include <string>
#include <queue>
using namespace std;

struct Node {
	string val;
	Node* left = nullptr;
	Node* right = nullptr;
};
int flag;
string sp, tgt;
Node* T = nullptr;
Node* R = nullptr;
void getTree(Node*& h)
{
	string cur;
	cin >> cur;
	if (cur == sp) return;
	h = new Node;
	h->val = cur;
	getTree(h->left);
	getTree(h->right);
}

void prev(Node* h, Node* gp)
{
	if (!h) return;
	if (h != gp) cout << ',';
	cout << h->val;
	prev(h->left, gp);
	prev(h->right, gp);
}
bool j = false;
void in(Node* h)
{
	if (!h) return;
	in(h->left);
	if (j) cout << ',';
	cout << h->val; j = true;
	in(h->right);
}
void post(Node* h, Node* gp)
{
	if (!h) return;
	post(h->left, gp);
	post(h->right, gp);
	cout << h->val;
	if (h != gp) cout << ',';
}

bool find(Node* h)
{
	if (!h) return false;
	if (h->val == tgt) {
		if (flag == 0) {
			R->right = h->left;
			h->left = R;
		}
		else {
			R->right = h->right;
			h->right = R;
		}
		return true;
	}
	return find(h->left) || find(h->right);
}

int main()
{
	cin >> sp;
	getTree(T);
	getTree(R);
	cin >> tgt;
	cin >> flag;

	prev(T, T); cout << endl;
	in(T); cout << endl; j = false;
	post(T, T); cout << endl;
	cout << endl;
	prev(R, R); cout << endl;
	in(R); cout << endl; j = false;
	post(R, R); cout << endl;
	cout << endl;

	if (find(T)) {
		cout << "success\n\n";
		prev(T, T); cout << endl;
		in(T); cout << endl; j = false;
		post(T, T);
	}
	else {
		cout << "failed";
	}
	return 0;
}
